<template>
  <van-nav-bar title="标题" fixed>
    <template #right>
      <div class="image" v-if="isLogin" @click="toGouserInfo">
        <img :src="userImg" alt="" />
      </div>
      <span v-else @click="toGologin">未登录</span>
    </template>
  </van-nav-bar>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import { onBeforeMount } from "@vue/runtime-core";
import { useRouter } from "vue-router";
export default {
  setup() {
    const router = useRouter();
    const state = reactive({
      isLogin: false,
      userImg: "",
    });

    const getLoginStatus = () => {
      if (localStorage.getItem("token")) {
        state.isLogin = true;
        getUserInfo();
      }
    };
    const getUserInfo = () => {
      const userinfo = JSON.parse(localStorage.getItem("userinfo"));
      // console.log(userinfo);
      state.userImg = require(`../assets/image/avator/${userinfo.avatar}`);
    };
    const toGologin = () => {
      router.push("/login");
    };
    const toGouserInfo = () => {
      router.push("userinfo");
    };
    onBeforeMount(() => {
      getLoginStatus();
    });
    return {
      ...toRefs(state),
      getLoginStatus,
      toGologin,
      getUserInfo,
      toGouserInfo,
    };
  },
};
</script>

<style lang="less" scoped>
.image {
  width: 36px;
  height: 36px;
  img {
    width: 36px;
    height: 36px;
    border-radius: 50%;
  }
}
span {
  color: rgb(4, 0, 255);
}
.van-nav-bar__right {
  padding: 0;
}
</style>